#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "lwip/netifapi.h"
#include "lwip/api_shell.h"
#include "lwip/sockets.h"
#include "hi_task.h"
#include "oled_menu.h"
//#include "kv_store.h"

#define TCP_HTTP_PORT 80                //服务器端口，http为 80
#define SRV_HOST "www.baidu.com"        //网址
#define SRV_ADDR "14.215.177.39"   	    //服务器IP地址，ping网址获得

char sendbuf[1024] = {0};
char recvbuf[1024] = {0};
char databuf[50] = {0};
//用于记录当前时间
int year;
int date_month;
int date_day;
int hour;
int min;
int sec;

/*任务执行函数，启动TCP客户端*/
static int tcp_client_task() 
{
    struct sockaddr_in srv_addr = {0};      //服务端地址信息
    int ret = 0;
    int num = 0;
             
    //HTTP消息构造
    sprintf(sendbuf,"GET / HTTP/1.1\n"
                    "Host: %s\n\r\n", SRV_HOST);
    printf("sendbuf:\n%s\r\n",sendbuf);

    //创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1) {
        printf("tcp_client_task: create socket failed!\r\n");
        return -1;
    } else {
        printf("tcp_client_task: create socket success!\r\n");
    }

    //连接服务器
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = htons(TCP_HTTP_PORT);
    srv_addr.sin_addr.s_addr = inet_addr(SRV_ADDR);
    ret = connect(socket_fd, (struct sockarrd_in *)&srv_addr, sizeof(srv_addr));
    if (ret != 0) {
        printf("tcp_client_task: connect failed, error is %d\r\n", errno);
        return -1;
    } else {
        printf("tcp_client_task: connect success!\r\n");
        printf("tcp_client_task: accept server addr: %s\r\n", inet_ntoa(srv_addr.sin_addr));
    }

    //发送http请求消息
    ret = send(socket_fd, sendbuf, sizeof(sendbuf), 0);
    if(ret == -1){
        printf("tcp_client_task: send failed!\r\n");
    }

    //服务器端回送数据
    num = recv(socket_fd, recvbuf, sizeof(recvbuf), 0);
    if(num == -1){
        printf("tcp_client_task: recv failed!\r\n");
    }
    //printf(">>>RECV the msg is:\n%s\r\n", recvbuf);

    //穷举法查找时间
    int j = 0;
    for(int i=0; i<sizeof(recvbuf); i++){
        if(recvbuf[i] == 'D'){
            i++;
            if(recvbuf[i] == 'a'){
                i++;
                if(recvbuf[i] == 't'){
                    i++;
                    if(recvbuf[i] == 'e'){
                        i+=2;
                        while(recvbuf[i] != 'G'){
                            databuf[j] = recvbuf[i];
                            j++;
                            i++;
                        }
                        printf("Date get!\n");
                    }
                }
            }
        }
    }
    printf("Date:\n%s\n",databuf);
    
    closesocket(socket_fd);
    return 0;
}

//把拿到的时间换算一下，方便Oled显示
void GetNowTime(void)
{
    int i,j;
    //将月份换算成数字
    char month[13][5] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
	for(i=0; i<13; i++){
		if(strstr(databuf, month[i])){
            date_month = i + 1;
		    break;
	    }
    }
    printf("month = %d\n", date_month);

    //获取日期
    char number[11] = {'0','1','2','3','4','5','6','7','8','9'};
    for(i=0; i<11; i++){
		if((databuf[6] == number[i]) && databuf[6] != '0'){
            date_day = i * 10;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[7] == number[i])){
            date_day = date_day + i;
		    break;
	    }
    }
    printf("day = %d\n", date_day);

    //获取年份，下面都是一样的方法
    for(i=0; i<11; i++){
		if((databuf[13] == number[i]) && databuf[13] != '0'){
            year = i * 1000;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[14] == number[i] && databuf[14] != '0')){
            year = year + i * 100;
		    break;
	    }
    }
    for(i=0; i<11; i++){
		if((databuf[15] == number[i]) && databuf[15] != '0'){
            year = year + i * 10;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[16] == number[i])){
            year = year + i;
		    break;
	    }
    }
    printf("year = %d\n", year);

    //时
    for(i=0; i<11; i++){
		if((databuf[18] == number[i]) && databuf[18] != '0'){
            hour = i * 10;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[19] == number[i])){
            hour = hour + i + 8;
		    break;
	    }
    }
    //分
    for(i=0; i<11; i++){
		if((databuf[21] == number[i]) && databuf[21] != '0'){
            min = i * 10;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[22] == number[i])){
            min = min + i;
		    break;
	    }
    }
    //秒
    for(i=0; i<11; i++){
		if((databuf[24] == number[i]) && databuf[24] != '0'){
            sec = i * 10;
		    break;
	    }
    }
    for(i=0; i<11; i++){
        if((databuf[25] == number[i])){
            sec = sec + i;
		    break;
	    }
    }

    printf("Time = %d:%d:%d\n",hour, min, sec);

}

//补一个计时函数，就不用每次都请求一遍了，从当前时间开始计时
static unsigned int g_TimeTask_w;
const hi_task_attr TimeTaskAttr_w = {
    .task_prio = 20,
    .stack_size = 1024,
    .task_name = "BuggyNetworkTimeTask",
};
void *time_count_t(void * para)
{
    time_t time_sec = 0;
    time_t old_sec = 0;
    time(&time_sec);              //获取当前秒数
    old_sec = time_sec;           //更新旧的秒数
    while(1)
    {
        time(&time_sec);          //获取秒数保存到time_t变量
        if(time_sec != old_sec)   //如果秒数改变(计时达到1秒)
        {
            old_sec = time_sec;   //更新旧的秒数
            if(sec <= 59)
                sec++;            //计时秒数加1
            else
            {
                sec = 0;         //如果原秒数为59，则变为0
                if(min <=59)
                    min++;        //计时分钟加1
                else
                {
                    min = 0;     //如果分钟数为59，则变为0
                    hour++;       //计时小时数加1
                }
            }
            //printf("TimeCount --%02d:%02d:%02d\r", hour, min, sec);
        }
    }
}

hi_void tcp_client_demo(hi_void)
{
    int ret;
    tcp_client_task();
    GetNowTime();

    hi_task_create(&g_TimeTask_w,
        &TimeTaskAttr_w,
        time_count_t,
        NULL);
}
